<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <img
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="changeSku(item, val)"
            v-if="val.picture"
            :src="val.picture"
            :title="val.name"
          />
          <span
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="changeSku(item, val)"
            v-else
            >{{ val.name }}</span
          >
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>
import powerSet from '@/vender/power-set.js'
const spliter = '⭐️'
// 得到路径字典
const getPathMap = (skus) => {
  // 1 得到所有sku集合
  // 2 从所有sku筛选有效sku
  // 3 根据有效sku使用算法得到子集
  // 4 根据子集忘路径字典存储key-value
  const pathMap = {}
  skus.forEach((sku) => {
    if (sku.inventory > 0) {
      // 可选值数组拿到[1,2,3]=>
      const valueArr = sku.specs.map((spec) => spec.valueName)
      // console.log(valueArr)
      // 可选值数组 子集
      const valueArrPowerSet = powerSet(valueArr)
      // console.log(valueArrPowerSet)
      // 遍历子集 往pathMap插入数据
      valueArrPowerSet.forEach((arr) => {
        const key = arr.join(spliter)
        // console.log(key)
        // 给pathMap设置数据
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

const getSelectedValues = (specs) => {
  const arr = []
  specs.forEach((item) => {
    // 选中的按钮对象 ['F-G', undefined, undefined]
    const selectedVal = item.values.find((val) => val.selected)
    arr.push(selectedVal ? selectedVal.name : undefined)
  })
  return arr
}
// 更新按钮禁用状态,测试商品1369155859933827074
const updateDisabledStatus = (specs, pathMap) => {
  // 1 约定按钮状态由本身disabled数据控制
  specs.forEach((item, i) => {
    const selectedValues = getSelectedValues(specs)
    item.values.forEach((val) => {
      // 2 判断当前是否选中，是选中不用判断
      if (val.selected) return
      // 3 拿当前的值按照顺序套入选中的值数组
      selectedValues[i] = val.name
      // 4 提出undefined数据，按照分隔符拼接key
      const key = selectedValues.filter((value) => value).join(spliter)
      // 5 拿着key去路径字典中查找是否有数据，有可以点击，没有禁用
      val.disabled = !pathMap[key]
    })
  })
}
// 初始化选中规格
const initSelectedStatus = (goods, skuId) => {
  const sku = goods.skus.find((sku) => sku.id === skuId)
  if (sku) {
    goods.specs.forEach((spec, i) => {
      const value = sku.specs[i].valueName
      spec.values.forEach((val) => {
        val.selected = val.name === value
      })
    })
  }
}

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({
        specs: [],
        skus: []
      })
    },
    skuId: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    const pathMap = getPathMap(props.goods.skus)
    // console.log(pathMap)
    // 初始化选中规格状态
    initSelectedStatus(props.goods, props.skuId)
    // ⭐️组件初始化 更新按钮禁用状态
    updateDisabledStatus(props.goods.specs, pathMap)
    // 选中与取消：每一个按钮都有自己的状态selected
    const changeSku = (item, val) => {
      // 当按钮是禁用的阻止程序运行
      if (val.disabled) return
      if (val.selected) {
        val.selected = false
      } else {
        item.values.forEach((valueItem) => {
          valueItem.selected = false
        })
        val.selected = true
      }
      // ⭐️点击按钮 更新禁用状态
      updateDisabledStatus(props.goods.specs, pathMap)
      // console.log(getSelectedValues(props.goods.specs))
      // 将选择的规格信息传递给父组件 过滤undefined
      const validSelectedArr = getSelectedValues(props.goods.specs).filter(
        (v) => v
      )
      if (validSelectedArr.length === props.goods.specs.length) {
        const skuIds = pathMap[validSelectedArr.join(spliter)]
        const sku = props.goods.skus.find((sku) => sku.id === skuIds[0])
        emit('change', {
          skuId: sku.id,
          price: sku.price,
          oldPrice: sku.oldPrice,
          inventory: sku.inventory,
          // 颜色：黑色 产地：中国 尺寸：10cm
          specsText: sku.specs
            .reduce((p, n) => `${p} ${n.name}：${n.valueName}`, '')
            .replace(' ', '')
        })
      } else {
        emit('change', {})
      }
    }
    return { changeSku }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
